﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;

namespace SofireCodeGenerator.Core
{
    public class EntityGenerator
    {
        public string TableName { get; set; }

        public SqlGeneratorBase Generator { get; set; }

        public DataTable ColumnsTable { get; set; }

        public bool AllColumns { get; set; }

        public string ClassName { get; set; }

        public void Create(out string entityCode, out string xsqlCode)
        {
            TemplateOptions options = new TemplateOptions()
            {
                ClassName = ClassName,
                Namespace = "SofireEG",
                Items = new List<TemplateItem>(),
                ConstFieldTemplates = "ConstFieldTemplate.txt",
                EntityLoadableItemTemplates = "EntityLoadableItemTemplate.txt",
                PropertyTemplates = "PropertyTemplate.txt"
            };
            XSqlTemplateOpionts xsqlTemplate = new XSqlTemplateOpionts();
            xsqlTemplate.TableName = this.TableName;
            xsqlTemplate.Generator = this.Generator;

            foreach(DataRow row in this.ColumnsTable.Rows)
            {
                if(!this.AllColumns && row.Field<bool?>("IsSelected") == false) continue;

                var item = new TemplateItem()
                {
                    Parent = options,
                    FieldName = row.Field<string>("FiledName"),
                    PropertyName = row.Field<string>("AliasName"),
                    Comment = row.Field<string>("FieldComments")
                };
                item.PropertyType = row.Field<string>("FieldType");
                item.PropertyFullType = item.PropertyType == Types.ByteArray.Name ? "(Byte[])" : ("Convert.To" + item.PropertyType);
                if(row.Field<decimal?>("IsNullable") == 1 && item.PropertyType != Types.String.Name)
                {
                    item.PropertyType += "?";
                }
                options.Items.Add(item);
            }
            xsqlTemplate.Items = options.Items;
            entityCode = TemplateOptions.Create(options, "ClassTemplate.txt");
            xsqlCode = TemplateOptions.Create(xsqlTemplate, "XSql.txt");
        }
    }
}
